package com.mpyy.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.mpyy.service.ReadPropertyConfig;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.io.IOException;

/**
 * @PackageName:com.mpyy.config
 * @ClassName:SpringmvcConfig
 * @Date:2022-02-23:10:22
 * @Author: Tang Neng
 */
@Configuration
@ComponentScan(basePackages = {"com.mpyy.service" ,  "com.mpyy.tool"})
public class SpringConfiguration {
    public SpringConfiguration(){
        System.out.println("调用了SpringConfiguration构造方法");
    }

    //1、数据源bean
    @Bean("druidDataSource")
    public DataSource dataSource(ReadPropertyConfig readPropertyConfig){
        //实例化一个druid数据源
        DruidDataSource druidDataSource = new DruidDataSource();
        //注入数据源要依赖的连接数据库的配置信息(ReadPropertyConfig.class)
        druidDataSource.setDriverClassName(readPropertyConfig.getDriverClassName());
        druidDataSource.setUrl(readPropertyConfig.getUrl());
        druidDataSource.setUsername(readPropertyConfig.getUserName());
        druidDataSource.setPassword(readPropertyConfig.getPassWord());
        return druidDataSource;
    }

    //2、session工厂bean
    @Bean("sqlSessionFactoryBean")
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) throws IOException {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:*/*Mapper.xml"));
        sqlSessionFactoryBean.setTypeAliasesPackage("com.mpyy.pojo");
        return sqlSessionFactoryBean;
    }

    //3、基于代理接口dao动态生成代理实现类
    //替代方式:在spring配置bean类前通过@MapperScan("com.spring.spring.mybatis.dao") //扫描Mybatis的Mapper接口
    @Bean(value = {"mapperScannerConfigurer"})
    public MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactoryBean");
        mapperScannerConfigurer.setBasePackage("com.mpyy.dao");
        return mapperScannerConfigurer;
    }

    //4、声明式事务bean
    @Bean
    public DataSourceTransactionManager dataSourceTransactionManager(DataSource dataSource){
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(dataSource);
        return dataSourceTransactionManager;
    }
}
